// const fs = require('node:fs/promises')

// Execution Time: 8s
// CPU usage: 100%(one core)
// Memory usage: 45MB
// ;(async () => {
//   const fileHandle = await fs.open('file.txt', 'w')

//   console.time('start')
//   for (let i = 0; i < 1000000; i++) {
//     await fileHandle.write(` ${i} `)
//   }

//   console.timeEnd('start')
// })()

// Execution Time: 1.2s
// CPU usage: 26%(one core)
// Memory usage: 26MB
// const fs = require('node:fs')

// console.time('time')
// fs.open('file.txt', 'w', (err, fd) => {
//   for (let i = 0; i < 1000000; i++) {
//     fs.writeSync(fd, ` ${i} `)
//   }
//   console.timeEnd('time')
// })

// const fs = require('node:fs/promises')
// const { Buffer } = require('buffer')

// DON'T DO IT THIS WAY!
// Execution Time: 200ms
// CPU usage: 100%(one core)
// Memory usage: 200MB
// ;(async () => {
//   const fileHandle = await fs.open('file.txt', 'w')
//
//   console.time('start')
//   const stream = fileHandle.createWriteStream()
//   for (let i = 0; i < 1000000; i++) {
//     const buff = Buffer.from(` ${i} `, 'utf-8')
//     stream.write(buff)
//   }
//
//   console.timeEnd('start')
// })()

const fs = require('node:fs/promises')
const { Buffer } = require('buffer')

// DON'T DO IT THIS WAY!
// Execution Time: 200ms
// CPU usage: 100%(one core)
// Memory usage: 200MB
// ;(async () => {
//   const fileHandle = await fs.open('file.txt', 'w')

//   console.time('start')
//   const stream = fileHandle.createWriteStream()
//   for (let i = 0; i < 1000000; i++) {
//     const buff = Buffer.from(` ${i} `, 'utf-8')
//     stream.write(buff)
//   }

//   console.timeEnd('start')
// })()

;(async () => {
  const fileHandle = await fs.open('file.txt', 'w')

  console.time('time')
  const stream = fileHandle.createWriteStream()

  // console.log(stream.writableHighWaterMark) // 16384

  // const buff = Buffer.alloc(16383, 10)
  // console.log(stream.write(buff)) // true
  // console.log(stream.write(Buffer.alloc(1, 'a'))) // false
  // console.log(stream.write(Buffer.alloc(1, 'a'))) // false
  // console.log(stream.write(Buffer.alloc(1, 'a'))) // false

  // console.log(stream.writableLength) // 16386

  // stream.on('drain', () => {
  //   console.log('You can write more data now')
  //   console.log(stream.write(Buffer.alloc(16384, 'a')))
  //   console.log(stream.writableLength) // 16384;
  // })

  let i = 0
  const numberOfWrites = 1000000000

  const writeMany = () => {
    while (i < numberOfWrites) {
      const buff = Buffer.from(` ${i} `, 'utf-8')

      if (!stream.write(buff)) break
      if (i === numberOfWrites - 1) {
        return stream.end()
      }

      i++
    }
  }

  writeMany()

  stream.on('drain', () => {
    writeMany()
  })

  stream.on('finish', () => {
    console.timeEnd('time')
    fileHandle.close()
  })
})()
